package com.mqy.service;


import com.mqy.dao.HBaseUserLocationDao;
import com.mqy.entity.Page;
import com.mqy.entity.UserLocation;
import com.mqy.utils.DateUtils;
import com.mqy.utils.HbaseStringFilter;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;
import java.util.UUID;

/**
 * userLocation 实现类
 *
 * @author EVE
 */
@Repository
public class HBaseUserLocationDaoImpl implements HBaseUserLocationDao {

    //private static final Logger logger = LoggerFactory.getLogger(HbaseSaltUserLocationDaoImpl.class);
    @Autowired
    @Qualifier("phoenixJdbcTemplate")
    private JdbcTemplate jdbcTemplate;
    String TableName = "userLocation"; //正式
   // @Value("${userlocation}")
   // String TableName ; //正式 加盐表

    //   String TableName = "userLocationtest";  //测试
    @Override
    public Page<UserLocation> query(UserLocation userLocation, Page<UserLocation> page) {
        //logger.info("【HBase】进入分页查询（userLocation）方法");
        if (userLocation == null || page == null || userLocation.getUserId() == null) {
           // logger.error("【HBase】（userLocation）入参userLocation或page为NULL");
            return null;
        }
        StringBuilder sb = new StringBuilder(" select userId,address,lng,lat,createTime as createTime2 from ").append
                (TableName).append(" where userId = ").append(userLocation.getUserId());
        if (page.getOrderBy() != null) {
            sb.append(" order by ").append(page.getOrderBy());
            if (page.getOrderDir() != null) {
                sb.append(" ").append(page.getOrderDir());
            }
        }
        String sql = sb.toString();
        sql = sql + " limit " + page.getPageSize() * page.getPageNo();
        List<UserLocation> userLocationList;
        try {
            long startTime = System.currentTimeMillis();
            userLocationList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(UserLocation.class));
            long endTime = System.currentTimeMillis();
            float excTime = (float) (endTime - startTime) / 1000;
            //分页代码
            int pageSize = page.getPageSize();
            int pageNo = page.getPageNo();
            // 第PageNo页 起始位置
            int pageRemoveNum = 0;
            int total = new Long(count(userLocation)).intValue();
            if (total > 0) {
                pageRemoveNum = (pageNo - 1) * pageSize < total ? (pageNo - 1) * pageSize : (total - pageSize > 0 ?
                        total : 0);
            }
            userLocationList = userLocationList.subList(pageRemoveNum, userLocationList.size());
            Long totalCount = count(userLocation);
            page.setTotalCount(totalCount);
            page.setResult(userLocationList);
            return page;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<UserLocation> query(String whereSql) {
        if (StringUtils.isBlank(whereSql)) {
            return null;
        }
        String sql = "select userId,address  from " + TableName + whereSql;
        sql += " limit 800 ";
        List<UserLocation> userLocationList = getUserLocations(sql);
        if (userLocationList != null) {
            return userLocationList;
        }
        return null;
    }

    private List<UserLocation> getUserLocations(String sql) {
        try {
            long startTime = System.currentTimeMillis();
            List<UserLocation> userLocationList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(UserLocation
                    .class));
            long endTime = System.currentTimeMillis();
            float excTime = (float) (endTime - startTime) / 1000;
            return userLocationList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<UserLocation> query(UserLocation userLocation, boolean sort) {
        if (userLocation == null || userLocation.getUserId() == null) {
            return null;
        }
        String sql = "select userId,address,lng,lat,createTime as createTime2  from " + TableName + " where userId = " +
                "" + userLocation.getUserId();
        if (sort) {
            //由于几处调用均是以 createTime 字段排序 所以将这个字段直接写死
            sql += "  order by createTime  desc ";
        }
        sql += " limit 800 ";
        List<UserLocation> userLocationList = getUserLocations(sql);
        if (userLocationList != null) {
            return userLocationList;
        }
        return null;
    }

    @Override
    public void add(UserLocation userLocation) {
        if (userLocation == null) {
            return;
        }
        String sql = "upsert into  " + TableName + " values (?,?,?,?,?,?)";
        Object args[] = new Object[6];
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
        args[0] = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16);
        args[1] = userLocation.getUserId();
        args[2] = HbaseStringFilter.stringFilter(userLocation.getAddress());
        args[3] = userLocation.getLng();
        args[4] = userLocation.getLat();
        args[5] = simpleDateFormat.format(userLocation.getCreateTime());
        //    args[5] = userLocation.getCreateTime();
        try {
            long startTime = System.currentTimeMillis();
            jdbcTemplate.update(sql, args);
            long endTime = System.currentTimeMillis();
            float excTime = (float) (endTime - startTime) / 1000;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<UserLocation> queryNewTimeAddress(UserLocation userLocation) {
        if (userLocation == null || userLocation.getUserId() == null) {
            return null;
        }
        String sql = "select address,createTime as createTime2 from " + TableName + "  where userId = " +
                userLocation.getUserId() + " order by createTime desc limit 1";
        return getUserLocations(sql);
    }

    @Override
    public Long count(UserLocation userLocation) {
        if (userLocation == null || userLocation.getUserId() == null) {
            return null;
        }
        String pageSql = " select count(1) from " + TableName + " where userId = " + userLocation.getUserId();
        Long totalCount = 0L;
        try {
            totalCount = jdbcTemplate.queryForObject(pageSql, Long.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return totalCount;
    }

    /**
     * 根据userId跟创建时间查询用户位置信息
     */
    public List<UserLocation> queryByUserIdAndTime(UserLocation userLocation) {
        if (userLocation == null || userLocation.getUserId() == null) {
            return null;
        }
        String sql = "select userId,createTime,lng,lat from " + TableName + "  where userId = " + userLocation.getUserId() + " and createTime <=" + "to_date('" + DateUtils.format(userLocation.getCreateTime(), "yyyy-MM-dd HH:mm:ss.SSS") + "')" + " order by createTime desc limit 1";
        return getUserLocations(sql);
    }
}
